<template>
  <div></div>
</template>

<script>
import * as XLSX from "xlsx-js-style";
import FileSaver from 'file-saver'
export default {
  name: "exportOrderExcel",
  data() {
    return {}
  },
  methods: {
    //报价单
    exportWarehouseOrder(row) {
      let params = {
        orderId: row.id,
        type: 1,
      }
      this.$api.orderGetOfferDirectoryDown(params).then((res) => {
        if (res.length == 0) {
          this.$message('暂无报价单数据!')
          return
        }
        if (!row.expressCharge) row.expressCharge = 0
        const wb = XLSX.utils.book_new();
        let data = [
          ['零食很忙门店货架报价清单'],
          [''],
          ["门店名称:", "", '门店负责人：'],
          ['产品名称', '规格', '单价', '数量', '总价']]
        res.map(el => {
          data.push([el.directoryName, el.norms, el.directoryFee, el.directoryCount, el.money])
        })

        data.push(['运费（元/公里）：'])
        data.push(["", "", "", '合计：', ""])
        const ws = XLSX.utils.aoa_to_sheet(data);
        ws['!cols'] = [
          {wpx: 250}, // 第一列宽度为100单位
          {wpx: 150},
          {wpx: 100},
          {wpx: 100},
          {wpx: 100},
          {wpx: 100},
          {wpx: 100}
        ];
        ws['!rows'] = [
          {hpt: 15}, // 第0行 大标题（合并了两行，所以高度大一些）
          {hpt: 15}, // 第1行 （大标题合并区域第二行）
          {hpt: 30}, // 第2行 门店信息
          {hpt: 25}, // 第3行 表头
        ]
        for (let i = 4; i < data.length; i++) {
          ws['!rows'][i] = {hpt: 30}
        }
        ws["A1"].s = {
          alignment: {horizontal: 'center'},
          font: {bold: true, sz: 20, color: {rgb: '000000'}},
          // fill: {fgColor: {rgb: ''}}
        }
        ws["A1"].hpt = 140;
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        ws['!merges'] = [
          {s: {r: 0, c: 0}, e: {r: 1, c: 4}},
          {s: {r: 2, c: 0}, e: {r: 2, c: 1}}, // “门店名称”合并两列
          {s: {r: 2, c: 2}, e: {r: 2, c: 3}}, // “门店负责人”合并两列
        ]
        const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
        for (let R = range.s.r; R <= range.e.r; R++) {
          for (let C = range.s.c; C <= range.e.c; C++) {
            const cellAddress = {r: R, c: C} // 获取单元格地址
            const cell = ws[XLSX.utils.encode_cell(cellAddress)]
            if (cell) {
              cell.s = cell.s || {} // 初始化样式
              cell.s.alignment = {
                horizontal: 'center', // 水平居中
                vertical: 'center', // 垂直居中
              }
            }
          }
        }
        // this.mergeSameCells(ws, data, 0);
        const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
        // 创建一个 Blob 对象
        const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'});
        // 使用 Blob 对象创建一个链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${row.storeName}报价单.xlsx`;

        // 触发下载
        link.click();
        // 清理
        URL.revokeObjectURL(link.href);

        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }
      })
    },
    //  合同列表
    exportContractList(val) {
      this.$api
          .contractGetContractList({
            pageSize: 10000,
            pageNumber: 1,
            systemType: val,
          })
          .then((res) => {
            const wb = XLSX.utils.book_new()
            let data = []
            data = [['序号  ', '店铺名', '联系人', '身份证', '总金额']]
            res.map((el, index) => {
              data.push([
                index + 1,
                el.storeName,
                el.customerName,
                el.customerIdCard,
                el.totalPrice,
              ])
            })
            const ws = XLSX.utils.aoa_to_sheet(data)
            ws['!cols'] = [
              {wpx: 50}, // 第一列宽度为250单位
              {wpx: 200}, // 第二列宽度为300单位
              {wpx: 100}, // 第三列宽度为350单位
              {wpx: 200},
              {wpx: 100},
            ]
            ws['A1'].s = {
              alignment: {horizontal: 'center'},
              font: {blod: true, color: {rgb: '000000'}},
              fill: {fgColor: {rgb: 'ff6a00'}},
            }
            // ws["A2"].s = {
            //   alignment: { horizontal: 'center' },
            // }
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

            ws['!merges'] = []
            const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'})

            // 创建一个 Blob 对象
            const blob = new Blob([s2ab(wbout)], {
              type: 'application/octet-stream',
            })

            // 使用 Blob 对象创建一个链接
            const link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.download = `合同列表.xlsx`

            // 触发下载
            link.click()

            // 清理
            URL.revokeObjectURL(link.href)

            function s2ab(s) {
              const buf = new ArrayBuffer(s.length)
              const view = new Uint8Array(buf)
              for (let i = 0; i !== s.length; ++i)
                view[i] = s.charCodeAt(i) & 0xff
              return buf
            }
          })

    },
    //  成本导出
    exportCost(val) {
      this.$api['newOrderCosts']({id: val.id}).then(({costs = []}) => {
        this.$quinn.expTable({
          fileName: `${val.storeName}-成本`,
          data: [costs],
          columns: [
            {label: '杂项成本', prop: 'additionCost'},
            {label: '产品成本', prop: 'materialCost'},
            {label: '安装成本', prop: 'installCost'},
            {label: '售后成本', prop: 'afterSaleCost'},
            {label: '总成本', prop: 'totalCost'},
            {label: '报价单', prop: 'saveOrder'},
          ],
        })
      })
    },
    //货架清单下载
    shelves(val) {
      this.$message.success('正在下载，请稍等...')
      let dataArr = []
      return this.$api.newOrderMaterialList({id: val.id}).then((res) => {
        this.$api.newOrderAdditionList({id: val.id}).then((res2) => {
          dataArr = [...res, ...res2]
          this.exportExcel({
            data: dataArr,
            sort: false,
            group: true,
            defaultTitle: `货架清单-${val.storeName}`,
            productMap: window?.g_config?.productMap2 || {},
            productSort: window?.g_config?.productSort2 || [],
            productColumns: window?.g_config?.productColumns2 || {},
          })
        })
      })
    },
    //仓储货架清单下载
    warehouseDown(val) {
      this.$message.success('正在下载，请稍等...')
      let dataArr = []
      return this.$api.newOrderStorageList({id: val.id}).then((res) => {
        this.$api.newOrderAdditionList({id: val.id}).then((res2) => {
          dataArr = [...res, ...res2]
          this.exportExcel({
            data: dataArr,
            sort: false,
            group: true,
            defaultTitle: `仓储货架清单-${val.storeName}`,
            productMap: window?.g_config?.productMap2 || {},
            productSort: window?.g_config?.productSort2 || [],
            productColumns: window?.g_config?.productColumns2 || {},
          })
        })
      })
    },
    exportExcel(props) {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1 // 月份从0开始，所以要加1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      let {
        sort = true,
        headers = [
          [
            '序号',
            '产品编码',
            '配件名称',
            '规格',
            '单位',
            '颜色',
            '总数量',
            '拣货签名',
            `下载时间${year}-${month}-${day} ${hour}:${minute}:${second}`,
          ],
        ],
        datamerges = [],
        defaultTitle = '出库单',
        type = 'file',
        productMap = window?.g_config?.productMap || {},
        productSort = window?.g_config?.productSort || [],
        productColumns = window?.g_config?.productColumns || {},
        group = true,
        data,
      } = props
      if (sort)
        data = data.sort(
            (a, b) =>
                productSort.indexOf(a.productCode) -
                productSort.indexOf(b.productCode)
        )
      const withAddition = data.filter(
          (item) => item.isAddition == 1 || item.isAddition == 2
      )
      const noAddition = data.filter((item) => item.isAddition == 0)
      data = noAddition.map((e, i) => {
        const {productCode, productName, norms, unit, count, colour} = e
        return {
          i: i + 1,
          productCode,
          productName,
          norms,
          unit,
          colour,
          count,
          s: {
            alignment: {
              horizontal: 'center', //水平居中
            },
          },
        }
      })
      let key = ''
      if (group)
          // return console.log(data);
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          const k = productMap[item.productCode]
          // return console.log(k,);
          if (k != key) {
            data.splice(i, 0, {
              i: k,
              // warehousePosition: k,
              productCode: k,
              productName: k,
              norms: k,
              unit: k,
              colour: k,
              count: k,
            })
            datamerges.push({
              s: {r: i + 1, c: 0},
              e: {r: i + 1, c: headers[0].length - 1},
            })
            i++
            key = k
          }
        }
      // return;
      data[data.length + 1] = ['']
      withAddition.map((el, index) => {
        data.push({
          i: index + 1,
          // warehousePosition: el.warehousePosition,
          productCode: el.productCode,
          productName: el.productName,
          norms: el.norms,
          unit: el.unit,
          colour: el.colour,
          count: el.count,
          s: {
            alignment: {
              horizontal: 'center', //水平居中
            },
          },
        })
      })
      const ws = XLSX.utils.book_new()
      XLSX.utils.sheet_add_aoa(ws, headers)
      XLSX.utils.sheet_add_json(ws, data, {
        origin: 'A' + (headers.length + 1),
        skipHeader: true,
      })
      let wscols = [
        {wch: 6},
        {wch: 15},
        {wch: 15},
        {wch: 35},
        {wch: 15},
        {wch: 10},
        {wch: 15},
        {wch: 15},
        {wch: 35},
      ]
      ws['!cols'] = wscols
      ws['!merges'] = datamerges

      for (const key in ws) {
        if (
            key.indexOf('!') === -1 &&
            Object.hasOwnProperty.call(ws, key) &&
            Object.hasOwnProperty.call(ws[key], 'v')
        ) {
          ws[key].s = {
            ...(ws[key].s || {}),
            alignment: {
              horizontal: 'center',
              vertical: 'center',
              wrap_text: true,
            },
            ...(Object.keys(productColumns).includes(ws[key].v)
                ? {
                  fill: {
                    fgColor: {rgb: '43CD80'},
                  },
                }
                : {}),
          }
        }
      }

      const wb = {
        Sheets: {
          Sheet1: ws,
        },
        SheetNames: ['Sheet1'],
      }
      var title = defaultTitle || '列表'
      const wopts = {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary',
      }
      const blob = new Blob([s2ab(XLSX.write(wb, wopts))], {
        type: 'application/octet-stream',
      })
      title = title + '.' + (wopts.bookType == 'biff2' ? 'xls' : wopts.bookType)
      if (type == 'blob') return new File([blob], title)
      FileSaver.saveAs(blob, title)
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i)
          view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
    },
  }
}
</script>

<style scoped>

</style>